package org.keyuan.service.impl;

import java.util.LinkedList;
import java.util.List;

import org.compass.core.CompassCallback;
import org.compass.core.CompassException;
import org.compass.core.CompassHits;
import org.compass.core.CompassSession;
import org.keyuan.entity.Book;
import org.keyuan.util.PageUtil;

public class QuerySearchBook implements CompassCallback<PageUtil<Book>>{
	private String keyword;
	private int curentPage;
	private int maxResults;
	
	public QuerySearchBook(String keyword,int curentPage,int maxResults){
		this.keyword=keyword;
		this.curentPage=curentPage;
		this.maxResults=maxResults;
	}
	
	@Override
	public PageUtil<Book> doInCompass(CompassSession session)
			throws CompassException {
		CompassHits hits=session.find(keyword);
		PageUtil<Book> pageUtil=new PageUtil<Book>();
		pageUtil.setCurrentPage(curentPage);
		pageUtil.setPageSize(maxResults);
		pageUtil.setTotal(hits.length());
		int length=pageUtil.getFristIndex()+maxResults;
		if(length>pageUtil.getTotal()){
			length=pageUtil.getTotal();
		}
		//System.out.println(pageUtil.getTotal());
		List<Book> books=new LinkedList<Book>();
		for (int i = pageUtil.getFristIndex(); i < length; i++) {
			Book book=(Book)hits.data(i);
			if(hits.highlighter(i).fragment("bookName")!=null)
				book.setBookName(hits.highlighter(i).fragment("bookName"));
			books.add(book);
		}
		pageUtil.setPagingData(books);
		return pageUtil;
	}

}
